package com.eques.demo

import android.annotation.SuppressLint
import android.content.Intent
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.Manifest
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.eques.base.BaseActivity
import com.eques.database.dao.DevListDao
import com.eques.event.EventTotalThread
import com.eques.icvss.core.module.user.BuddyType
import com.eques.icvss.utils.ELog
import com.eques.service.DoorBellService
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class IncomingActivity : BaseActivity() {
    private lateinit var img_view: ImageView
    private lateinit var btn_accept: ImageView
    private lateinit var btn_reject: ImageView
    private val TAG: String? = IncomingActivity::class.simpleName
    private var channelId = -1
    private lateinit var devId: String
    private lateinit var devDao: DevListDao
    private lateinit var userName: String
    private var devRole= BuddyType.TYPE_WIFI_DOOR_VM5
    private var mediaPlayer: MediaPlayer? = null

    companion object {
        private const val REQUEST_RECORD_AUDIO_PERMISSION = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_incoming)
        EventBus.getDefault().register(this)
        devId = intent.getStringExtra("devId")!!
        channelId = intent.getIntExtra("channelId", -1)
        initDevInfo()
        initData()
        initView()
        playRingtone()
    }

    private fun initDevInfo() {
        userName = preference.getString(Config.EQUES_USER_NAME)!!
        devDao = BaseAppApplication.Companion.instance!!.getYkDao(this)
        CoroutineScope(Dispatchers.IO).launch {
            val devList = devDao.getBdyListEntry(userName, devId)
            ELog.e("设备详细信息", devList)
            if (devList != null) {
                devRole=devList.role
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            235->{
                if (channelId < 0) {
                    channelId = event.intMsg
                }
            }
            Config.INCOMING_CALL_PREVIEW -> {
                //门铃来电缩略图
                val incomingDevBid: String = event.stringMsg!!
                val serverContext = event.stringMsgParam_one
                val doorbellFid = event.stringMsgParam_two
                Log.e(TAG, "门铃图：$doorbellFid")
                if (devId == incomingDevBid) {
                    val url: String = DoorBellService.icvss!!.equesGetRingPictureUrl(
                        doorbellFid,
                        incomingDevBid,
                        serverContext,
                        "fid"
                    ).toString()
                    Log.e(TAG, "门铃图url：$url")
                    Glide.with(this@IncomingActivity)
                        .load(url)
                        .into(img_view)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        stopRingtone()
    }

    override fun initView() {
        img_view = findViewById(R.id.img_view)
        btn_accept = findViewById(R.id.btn_accept)
        btn_reject = findViewById(R.id.btn_reject)

        btn_accept.setOnClickListener{
            requestAudioPermission()
        }

        btn_reject.setOnClickListener{
            stopRingtone()
            finish()
        }
    }

    override fun initData() {
    }

    private fun playRingtone() {
        try {
            val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
            mediaPlayer = MediaPlayer.create(this, ringtoneUri)
            mediaPlayer?.isLooping = true
            mediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun stopRingtone() {
        try {
            mediaPlayer?.let { player ->
                if (player.isPlaying) {
                    player.stop()
                }
                player.release()
                mediaPlayer = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun requestAudioPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                REQUEST_RECORD_AUDIO_PERMISSION
            )
        } else {
            proceedToCall()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_RECORD_AUDIO_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    proceedToCall()
                } else {
                    Toast.makeText(this, "需要录音权限才能进行通话", Toast.LENGTH_SHORT).show()
                }
                return
            }
        }
    }

    private fun proceedToCall() {
        stopRingtone()
        if(devRole== BuddyType.TYPE_WIFI_DOOR_VL4 || devRole== BuddyType.TYPE_WIFI_DOOR_VM2C){
            //走UDP
            DoorBellService.icvss!!.iot.activeCall(true, 0, 0, 0)
        }else{
            //走TCP
            DoorBellService.icvss!!.iot.activeCall(false, 0, 0, 0)
        }
        val intent = Intent(this, VideoCallActivity::class.java)
        intent.putExtra("devId", devId)
        intent.setPackage(packageName)
        intent.putExtra("channelId", channelId)
        startActivity(intent)
        finish()
    }
}
